package com.webtest.mvctest3;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/15 15:13
 * <p>
 * 自定义的HttpFilter，实现自Filter接口
 */
public abstract class AbstractHttpFilter implements Filter {
    private FilterConfig filterConfig;

    /**
     * 直接返回FilterConfig对象
     *
     * @return
     */
    public FilterConfig getFilterConfig() {
        return filterConfig;
    }

    /**
     * 不建议子类直接覆盖，若直接覆盖，则可能造成成员变量为空
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        init();
    }

    /**
     * 原生的doFilter方法，在方法内部将ServletRequest和ServletResponse转换成了HttpServletRequest和HttpServletResponse并调用了doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)方法
     * <p>
     * 若编写Filter的过滤方法，不建议直接继承该方法，而建议继承
     * doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        doFilter(request, response, filterChain);
    }

    @Override
    public void destroy() {

    }

    /**
     * 抽象方法：
     * 适合http开发的doFilter
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    protected abstract void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException;

    /**
     * 共子类继承的自定义初始化方法
     */
    protected abstract void init();
}
